import os
import json

# 获取当前文件所在目录的绝对路径
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
# 构建相对于当前文件的游戏根目录
GAME_DIR = os.path.dirname(os.path.dirname(CURRENT_DIR))
# 构建数据文件的绝对路径
DATA_DIR = os.path.join(GAME_DIR, "data")
DATA_PATH = os.path.join(DATA_DIR, "game_characters.json")


def save_characters(all_chars): 
    """Save character data to a JSON file.
    
    Args:
        all_chars (list): List of character dictionaries to save
        
    Raises:
        TypeError: If all_chars is not a list
        PermissionError: If there's no permission to write to the file
        Exception: For any other errors during saving
    """
    try:
        # Ensure data directory exists
        if not os.path.exists(DATA_DIR):
            os.makedirs(DATA_DIR)
            print(f"Created data directory: {DATA_DIR}")
        
        # Validate data format
        if not isinstance(all_chars, list):
            raise TypeError("Character data must be a list")
        
        # Save data
        with open(DATA_PATH, "w", encoding="utf-8") as f:
            json.dump(all_chars, f, ensure_ascii=False, indent=2)
        print(f"✅ All characters successfully saved to: {DATA_PATH}")
        print(f"✅ Saved {len(all_chars)} characters")
    except TypeError as type_error:
        print(f"❌ Data type error: {str(type_error)}")
        raise
    except PermissionError:
        print(f"❌ Permission error: No permission to write to {DATA_PATH}")
        raise
    except Exception as e:
        print(f"❌ Failed to save data: {str(e)}")
        raise

def load_characters():
    """Load character data from a JSON file.
    
    Returns:
        list: List of character dictionaries loaded from file, or empty list if file not found or error occurs
    """
    print(f"DEBUG: Attempting to load file: {DATA_PATH}")
    try:
        # Ensure data directory exists
        if not os.path.exists(DATA_DIR):
            os.makedirs(DATA_DIR)
            print(f"Created data directory: {DATA_DIR}")
        
        # Try to load file
        if os.path.exists(DATA_PATH):
            with open(DATA_PATH, "r", encoding="utf-8") as f:
                all_chars = json.load(f)
                # Validate loaded data format
                if not isinstance(all_chars, list):
                    print(f"❌ Data format error: Data in file {DATA_PATH} is not in list format")
                    return []
                print(f"✅ Successfully loaded {len(all_chars)} characters")
                return all_chars
        else:
            print(f"ℹ️  Data file {DATA_PATH} does not exist, creating empty character list")
            return []
    except json.JSONDecodeError as json_error:
        print(f"❌ JSON parsing error: {str(json_error)}")
        print(f"ℹ️  File {DATA_PATH} has incorrect format, returning empty character list")
        return []
    except PermissionError:
        print(f"❌ Permission error: No permission to read {DATA_PATH}")
        return []
    except Exception as e:
        print(f"❌ Error loading data: {str(e)}")
        return []


    
